#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <sys/types.h>          /* See NOTES */
#include    <sys/socket.h>
#include	<sys/time.h>
#include    <errno.h>
#include    <netinet/in.h>
#include    <arpa/inet.h>
#include    <fcntl.h>
#include	<unistd.h>  

#define P_FIFO   "/tmp/pro_fifo"

char InputBuffer[4096] = {0};

void sendMsgToServer(char* msg, int dataSize)
{
	//创建套接字,即创建socket   
	int clt_sock = socket(AF_INET, SOCK_STREAM, 0);   
	if(clt_sock < 0)  
	{  
	  //创建失败  
		printf("{\"msg\":\"服务未启动\"}\n");
	//          perror("socket");  
		return;  
	}
	fd_set fdSet;
	struct timeval t;
	struct timeval t2;
	t.tv_sec = 2;
	t.tv_usec = 0;
	FD_ZERO(&fdSet);
	FD_SET(clt_sock, &fdSet);

	//绑定信息，即命名socket   
	struct sockaddr_in addr;   
	addr.sin_family = AF_INET;   
	addr.sin_port = htons(6002);   
	//inet_addr函数将用点分十进制字符串表示的IPv4地址转化为用网络   
	//字节序整数表示的IPv4地址   
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	//不需要监听  

	//发起连接  
	//    struct sockaddr_in peer;  
	socklen_t addr_len = sizeof(addr);
	int connect_fd = connect(clt_sock, (struct sockaddr*)&addr, addr_len);  
	if(connect_fd < 0)  
	{  
	  printf("connect failed!\n");
	  perror("connect");  
	  return;  
	}

	int flags;
	if(flags = fcntl(clt_sock, F_GETFL, 0) < 0)
	{
		perror("fcntl");
		return;
	}
	flags |= O_NONBLOCK;
	if(fcntl(clt_sock, F_SETFL, flags) < 0)
	{
		perror("fcntl");
		return;
	}

	int ret = write(clt_sock, msg, dataSize);


	FD_ZERO(&fdSet);
	FD_SET(clt_sock, &fdSet);

	int sel = select(clt_sock+1, &fdSet, 0, 0 , &t);
	
	t.tv_sec = 0;
	t.tv_usec = 100000;
	//printf("sel:%d\n", sel);
	
	if(sel > 0)
	{
		while(1)
		{
			FD_ZERO(&fdSet);
			FD_SET(clt_sock, &fdSet);

			sel = select(clt_sock+1, &fdSet, 0, 0 , &t);
			if(sel<=0)
				return;
			memset(InputBuffer, 0, sizeof(InputBuffer));
			ret = read(clt_sock, InputBuffer, sizeof(InputBuffer));
			if(ret <=0)
			{

				break;
			}
			printf("%s", InputBuffer);
		}
		printf("\n");
	}
	close(connect_fd);
}

int main(int argc, char*argv[])
{
    int ContentLength;	// 数据长度
    int i,x;
    char *p;
    char *pRequestMethod; 	// METHOD属性值
    setvbuf(stdin, NULL, _IONBF, 0); // 关闭stdin的缓冲
    printf("Content-type:application/json\r\n"); // 从stdout中输出，告诉Web服务器返回的信息类型
    printf("\n"); // 插入一个空行，结束头部信息
	//char test[] = "hello";
	//sendMsgToServer(test, sizeof(test));
    // 从环境变量REQUEST_METHOD中得到METHOD属性值
    pRequestMethod = getenv("REQUEST_METHOD");
    if (pRequestMethod == NULL)
    {
        printf("<p>request = null</p>"); 
        return 0;
    }
    if (strcasecmp(pRequestMethod, "POST") == 0)
    {
              //printf("<p>OK the method is POST!\n</p>");
        p = getenv("CONTENT_LENGTH");     //从环境变量CONTENT_LENGTH中得到数据长度
        if (p != NULL)
            ContentLength = atoi(p);
        else
            ContentLength = 0;
        if (ContentLength > sizeof(InputBuffer) - 1)
            ContentLength = sizeof(InputBuffer) - 1;
        i = 0;
        while (i < ContentLength)
        {                         //从stdin中得到Form数据
            x = fgetc(stdin);
            if (x == EOF)
                break;
            InputBuffer[i++] = x;
        }
        InputBuffer[i] = '\0';
        ContentLength = i;
        //printf("%s\n", InputBuffer);
		sendMsgToServer(InputBuffer, ContentLength+1);
		//control(InputBuffer);
        //parseJson(InputBuffer);
        //	DecodeAndProcessData(InputBuffer);                 //具体译码和处理数据，该函数代码略
    }
    else if (strcasecmp(pRequestMethod, "GET") == 0)
    {
             //printf("<p>OK the method is GET!\n</p>");
        p = getenv("QUERY_STRING");     //从环境变量QUERY_STRING中得到Form数据
        if (p != NULL)
        {
			printf("%s\n",p);
			return 0;
            strcpy(InputBuffer, p);
            sendMsgToServer(InputBuffer, ContentLength+1);
        }
    }
    //   printf("<HEAD><TITLE>Submitted OK</TITLE></HEAD>\n");    //从stdout中输出返回信息
    //   printf("<BODY>The information you supplied has been accepted.</BODY>\n");
    return 0;
}


